/*年轻人，只管向前看，不要管自暴自弃者的话*/
package com.composetest.page.home

import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.composetest.core.model.Product
import com.composetest.core.model.ProductData
import com.composetest.core.network.HttpRequestManager
import kotlinx.coroutines.launch
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json


/**
 * create by itz on 2024-10-15 10:00
 * desc :
 **/
class HomeViewModel : ViewModel() {

    var datum by mutableStateOf<List<Product>>(emptyList())

    companion object {
        const val TAG = "HomeViewModel"
    }

    init {
        //datum = ProductData.products
        //testJSON()
        getProducts()
    }

    private fun testJSON() {
        val json = Json.encodeToString(datum[0])
        Log.d(TAG, "encodeToString: $json")

        val obj =
            Json.decodeFromString<Product>("""{"id":"1","title":"jin 408升十字对开双开四开门智能一级能效风冷无霜大容量","price":100.0,"originalPrice":199.0,"sales":1.0,"stock":2.0,"commentsCount":99}""")
        Log.d(TAG, "decodeFromString: $obj")
    }

    private fun getProducts(
        data: Map<String, String> = mapOf("page" to "1", "size" to "10"),
        app: String = "0"
    ) {
        viewModelScope.launch {
            HttpRequestManager.instance.products(data, app)?.let { datum = it }
        }
    }
}